import {Component, OnInit} from '@angular/core';
import {Router, ActivatedRoute} from "@angular/router";
import {OneDialogService} from "../../../../widgets/one-dialog/one-dialog.service";
import {SitesService} from "../sites.service";
import {ResponseUtil} from "../../../../util/response-util";
import {PageSubject} from "../../../../util/page-subject";
import {Path} from "../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {FormBuilder} from "@angular/forms";
import {TreeUtil} from "../../../../util/tree-util";
import {MsgResult} from "../../../../models/msg-result";
import {MsgConstants} from "../../../../constants/constants";
import {Site} from "../site";
import {DataStorageUtil} from "../../../../util/data-storage-util";

declare var $;

@Component({
  selector: 'app-study-code',
  templateUrl: './study-code.component.html'
})
export class StudyCodeComponent implements OnInit {

  site: Site;

  table;

  siteArr: Array<string> = [];

  regionCode: string;

  constructor(private router: Router,
              private route: ActivatedRoute,
              private pageSubject: PageSubject,
              private fb: FormBuilder,
              private dataStorageUtil: DataStorageUtil,
              private dialogService: OneDialogService,
              private treeUtil: TreeUtil,
              private responseUtil: ResponseUtil,
              private sitesService: SitesService,) {
  }

  ngOnInit() {
    this.pushPage();
    this.getRegionTree();
    this.initSiteFormData(this.siteArr);
  }

  /**
   * 面包屑
   */
  private pushPage() {
    let path = new Path("运维管理", "");
    this.pageSubject.pushPage("站点管理", "学习城市", path);
  }


  /**
   * 获取行政区划树
   */
  getRegionTree() {
    let regionCode = "0";
    this.sitesService.getRetrieveRegionsTree(regionCode).subscribe(
      result => this.responseUtil.success(result, this.processRegionsTreeResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   * 对行政区划树结果处理
   * @param result
   */
  private processRegionsTreeResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.regioCodezTree(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   *  行政区划树
   */
  private regioCodezTree(datasTree) {
    let datas = datasTree || [];
    // 新增中的树
    let userUpdateZtreeSetting = {
      view: {
        fontCss: this.setFontCss_ztree //设置字体颜色
      },
      callback: {
        onClick: this.userUpdateZtreeClick
      }
    };
    $.fn.zTree.init($("#user_update_orgTree"), userUpdateZtreeSetting, datas);
  }

  //同步到文本框
  userUpdateZtreeClick = (even, id, treeNode) => {
    this.regionCode = treeNode.id;
    this.getSiteDate(treeNode.id);
  }

  /**
   * 获取行政区划下的标准站点
   */
  private getSiteDate(regionId) {
    this.sitesService.getStandardSite(regionId, "").subscribe(
      result => this.responseUtil.success(result, this.processStandardSiteResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   * 对政标准站点结果处理
   * @param result
   */
  private processStandardSiteResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.initSiteFormData(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 搜索节点，并展开
   */
  enterSearch() {
    let inputValue = $("#serach_regionName").val();
    let treeId = "user_update_orgTree";
    this.treeUtil.searchTreeNode(treeId, inputValue);
  }

  /**
   * 设置树节点字体样式
   */
  private setFontCss_ztree(treeId, treeNode) {
    if (treeNode.id == 0) {
      //根节点
      return {color: "#333", "font-weight": "bold"};
    } else if (treeNode.isParent == false) {
      //叶子节点
      return (!!treeNode.highlight) ? {color: "#48ab5d", "font-weight": "bold"} : {
        color: "#333",
        "font-weight": "normal"
      };
    } else {
      //父节点
      return (!!treeNode.highlight) ? {color: "#48ab5d", "font-weight": "bold"} : {
        color: "#333",
        "font-weight": "normal"
      };
    }
  }

  /**
   * 初始化空气站标准站的站点
   * @param datas
   */
  initSiteFormData(datas) {
    $(".one-table-area").html('<table id="one_table_site"></table>');
    this.table = $('#one_table_site').bootstrapTable({
      columns: [
        {checkbox: true, width: 20},
        {field: "id", title: 'ID', align: 'left', visible: false, switchable: false},
        {field: "siteName", title: '站点名称', align: 'left', width: 150},
        {field: "siteTypeName", title: '站点类型', align: 'left', width: 20},
        {field: "siteCode", title: '站点编码', align: 'left', width: 100},
        {field: "regionCode", title: '行政区划码', align: 'left', width: 100},
        {field: "regionName", title: '学习城市', align: 'left', width: 50},
      ],
      data: datas,
      pagination: true,
      paginationLoop: false,
      paginationPreText: "上一页",
      paginationNextText: "下一页",
      undefinedText: "暂无数据",
      height: 700,//table高度
      pageSize: 15,
      pageList: [10, 15, 20],
      singleSelect: true,//单选
      clickToSelect: true,//点击选中
      classes: "table table-hover",
      striped: true,//隔行变色
      mobileResponsive: true//响应式
    });
  }

  /**
   * 站点名称搜索
   */
  search() {
    let siteName = $("#siteName").val();
    this.sitesService.getStandardSite(this.regionCode, siteName).subscribe(
      result => this.responseUtil.success(result, this.processStandardSiteResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   * 取消选取，
   * 1.如果修改页面选取学习城市，则传入一个路由id；
   * 2.判断路由id是否为空，为空跳到添加页面；
   * 3.否则跳到修改页面
   */
  cancelStudySite() {
    if (!!this.route.snapshot.params['siteId']) {
      let id = this.route.snapshot.params['siteId'];
      this.router.navigate(['../update', {siteId: id}], {relativeTo: this.route});
    } else {
      this.router.navigate(['../add', {tag: "tag"}], {relativeTo: this.route});
    }
  }

  /**
   * 保存选取的学习城市和站点
   * 1.如果路由id不为空，跳到修改页面，
   * 2.否则跳到添加页面
   */
  saveStudySite() {
    let rows = this.table.bootstrapTable('getSelections');
    if (rows.length > 0) {
      this.dataStorageUtil.set("studyRegionCode", rows[0].regionCode);
      this.dataStorageUtil.set("studyRegionName", rows[0].regionName);
      this.dataStorageUtil.set("studySiteCode", rows[0].siteCode);
      this.dataStorageUtil.set("studySiteName", rows[0].siteName);
    }else{
      this.dataStorageUtil.set("studyRegionCode", '');
      this.dataStorageUtil.set("studyRegionName", '');
      this.dataStorageUtil.set("studySiteCode", '');
      this.dataStorageUtil.set("studySiteName", '');
    }
    if (!!this.route.snapshot.params['siteId']) {
      let siteid = this.route.snapshot.params['siteId'];
      this.router.navigate(['../update', {id: siteid}], {relativeTo: this.route});
    } else {
      this.router.navigate(['../add', {tag: "tag"}], {relativeTo: this.route});
    }

  }


}
